package com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement

import android.app.Activity
import android.util.Log
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.MmoApplication
import com.horoscope.astrology.zodiac.signs.free.bean.ConfigResultBean
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.MyHandler
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.IronSourceInterstitialListener
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.IronSourceRewardListener
import com.ironsource.mediationsdk.IronSource
import com.ironsource.mediationsdk.logger.IronSourceError
import com.ironsource.mediationsdk.model.Placement
import com.ironsource.mediationsdk.sdk.InterstitialListener
import com.ironsource.mediationsdk.sdk.RewardedVideoListener
import com.jeremyliao.liveeventbus.LiveEventBus

class LoadIronSourceAd private constructor() {

    private val mContext = MmoApplication.getInstance()

    // 统计失败次数，过多停止循环加载
    private var insertLoadCount = 0
    private var rewardLoadCount = 0

    private var iPlacement = ""
    private var rPlacement = ""
    private var mRewardPlacement: Placement? = null
    private var mRewardPosition = 0

    private var mIronSourceInterstitialListener: IronSourceInterstitialListener? = null
    private var mIronSourceRewardListener: IronSourceRewardListener? = null

    // 当前所用的广告ID
    var iBean: ConfigResultBean.AdInfo? = null
    var rBean: ConfigResultBean.AdInfo? = null

    fun setIronSourceInterstitialListener(listener: IronSourceInterstitialListener) {
        mIronSourceInterstitialListener = listener
    }

    fun setIronSourceRewardListener(listener: IronSourceRewardListener) {
        mIronSourceRewardListener = listener
    }

    companion object {
        private const val TAG = "ironSourceSDK"
        val mInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            LoadIronSourceAd()
        }
    }


    /**interstitial广告数据准备，初始化对象，加载对象，显示广告**/

    // 数据已加载 初始化实例 添加监听 加载广告
    fun initInsertAD(bean: ConfigResultBean.AdInfo) {
        IronSource.loadInterstitial()
        iBean = bean
    }

    //Show the ad  插屏广告
    fun showInterstitialAD(placement: String, bean: ConfigResultBean.AdInfo, time: Int): Boolean {
        iPlacement = placement
        var showFlag = false
        try {
            if (IronSource.isInterstitialReady()) {
                supplement()
                MyHandler.instance?.let { it.post { IronSource.showInterstitial() } }
                FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Interstitial", "True_$time")
                showFlag = true
            } else {
                FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Interstitial", "False_$time")
                //没有加载，需要补充一次 num = 1
                AppSettingManager.saveInt(1, "supplement")
            }
        } catch (e: Exception) {
            e.printStackTrace()
            showFlag = false
        }
        return showFlag
    }

    /**interstitial广告数据准备，初始化对象，加载对象，显示广告**/


    /**rewardl广告数据准备，初始化对象，加载对象，显示广告**/
    // 奖励广告
    fun initIsRewardAd(activity: Activity, bean: ConfigResultBean.AdInfo) {
        rBean = bean
    }

    // show激励广告
    fun showRewardedVideoAd(
        bean: ConfigResultBean.AdInfo,
        placement: String,
        position: Int,
        time: Int
    ): Boolean {
        rPlacement = placement //用于打点
        mRewardPosition = position // 用于刷新指定item
        var isShow = false
        // 展示前判断即再次加载下一个视频
        if (IronSource.isRewardedVideoAvailable()) {
            MyHandler.instance?.let { it.post { IronSource.showRewardedVideo() } }
            FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Reward", "True_$time")
            isShow = true
        } else {
            FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Reward", "False_$time")
        }
        return isShow
    }

    /**rewardl广告数据准备，初始化对象，加载对象，显示广告**/

    // 是否正常显示了广告，在本地sp做记录
    private fun supplement() {
        val supplement = AppSettingManager.readInt("supplement", 0)
        if (supplement == 1) {//补充展示AD，标志位置0
            AppSettingManager.saveInt(0, "supplement")

            FlurryEventUtil.putDataToEvent(
                EventType.TYPE_AD_INTERSTITIAL_DISPLAY,
                "type",
                "Supplement"
            )
        } else {//正常展示广告
            FlurryEventUtil.putDataToEvent(
                EventType.TYPE_AD_INTERSTITIAL_DISPLAY,
                "type",
                "Correct"
            )
        }
    }

    private
    var mListener: AdClose? = null

    // Back页面监听Ad被关闭
    fun setOnAdCloseListener(listener: AdClose) {
        mListener = listener
    }

    // 用户对广告打开 or 关闭的回调
    interface AdClose {
        fun onClose()
        fun onOpen()
    }

    // IronSource 全屏、激励视频监听
    fun initListener() {
        //设置插页式监听器
        IronSource.setInterstitialListener(object : InterstitialListener {
            override fun onInterstitialAdClicked() {
                FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_CLICK, "type", iPlacement)
            }

            override fun onInterstitialAdReady() {
                mIronSourceInterstitialListener?.onIronSourceADLoad(iBean!!)
                Log.d("wsTest", "IS成功")
            }

            override fun onInterstitialAdLoadFailed(ironSourceError: IronSourceError) {
                // 广告加载失败时调用，可通过访问IronSourceError对象获取错误数据
//                if (insertLoadCount < 10) {
                mIronSourceInterstitialListener?.onIronSourceFailed(ironSourceError.errorMessage)
//                }
                Log.d("wsTest", "IS失败" + "错误内容" + ironSourceError.errorMessage)
                Log.d("wsTest", "IS失败" + "错误码" + ironSourceError.errorCode)
//
            }

            override fun onInterstitialAdOpened() {
                // 广告被打开始loadInterstitial()无效
            }

            override fun onInterstitialAdClosed() {
                // 广告关闭
                mListener?.onClose()
//                IronSource.loadInterstitial()
            }

            override fun onInterstitialAdShowSucceeded() {
                // 显示广告时loadInterstitial()无效
                if (iPlacement != "Supplement") { // 非补位
                    FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_DISPLAY, "type", iPlacement)
                }
            }

            override fun onInterstitialAdShowFailed(ironSourceError: IronSourceError) {}
        })

        // 设置IronSource奖励的视频监听器
        // IS的回调不一定都在主线程，在show之前要手动传递到主线程
        IronSource.setRewardedVideoListener(
            object : RewardedVideoListener {
                override fun onRewardedVideoAdOpened() {
                    // 视频被打开
                    FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_DISPLAY, "type", rPlacement)
                }

                override fun onRewardedVideoAdClosed() {
                    // 视频被关闭，在关闭时判断是否完整看完视频得到奖励
                    if (mRewardPlacement != null) {
                        LiveEventBus.get(rPlacement).post(mRewardPosition)
                        mRewardPlacement = null
                    }
                }

                override fun onRewardedVideoAvailabilityChanged(b: Boolean) {
                    // 当视频可用性更改时调用
                    if (b) {
                        mIronSourceRewardListener?.onIronSourceRewardLoad(rBean!!)
                    } else {
                        mIronSourceRewardListener?.onIronSourceRewardFailed()

                    }
                    Log.e(TAG, "RewardVideo=$b")
                }

                override fun onRewardedVideoAdRewarded(placement: Placement) {
                    // 视频获得奖励并可以向用户奖励后调用
                    mRewardPlacement = placement
                }

                override fun onRewardedVideoAdStarted() {}

                override fun onRewardedVideoAdEnded() {}

                override fun onRewardedVideoAdShowFailed(ironSourceError: IronSourceError) {}

                override fun onRewardedVideoAdClicked(placement: Placement) {}
            })
    }

}
